﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using NetWorkMsg;

namespace AIClient.Awaiters
{
    public class UnPackableAwaiterWrapper
    {
        private UnPackableAwaiter _awaiter;

        public UnPackableAwaiter GetAwaiter()
        {
            return _awaiter ?? (_awaiter = new UnPackableAwaiter());
        }

        public void SetResult(IUnPackable unPackable)
        {
            _awaiter?.SetResult(unPackable);
        }
    }

    // 等待服务器回调
    public class UnPackableAwaiter : INotifyCompletion
    {
        private IUnPackable _result;
        private Action      _continuation;

        public UnPackableAwaiter()
        {
            _result       = null;
            _continuation = null;
        }

        public bool IsCompleted => _result != null;

        // 缓存后续的状态,等服务器回调到达后执行
        public void OnCompleted(Action action)
        {
            _continuation = action;
        }

        public void SetResult(IUnPackable result)
        {
            _result = result;
            _continuation();
            _result       = null;
            _continuation = null;
        }

        public IUnPackable GetResult()
        {
            return _result;
        }
    }
}